package com.interview.item.javabase.cookie;

import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @Author:zxh
 * @Description: cookie的set值和get值的 演示
 * @Date: 2020/4/5
 * @Modified By:
 */
public class cookieDemo {
    @Autowired
    HttpServletRequest request;

    /**
     * 获得指定Cookie的值
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param name     名字
     * @param isRemove 是否移除
     * @return 值
     */
    public static String getCookie(HttpServletRequest request, HttpServletResponse response, String name, boolean isRemove) {
        String value = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    try {
                        value = URLDecoder.decode(cookie.getValue(), "utf-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (isRemove) {
                        cookie.setMaxAge(0);
                        response.addCookie(cookie);
                    }
                }
            }
        }
        return value;
    }


    /**
     * 设置 Cookie
     *
     * @param name   名称
     * @param value  值
     * @param maxAge 生存时间（单位秒）
     * @param uri    路径
     */
    public static void setCookie(HttpServletResponse response, String name, String value, String path, int maxAge) {
        Cookie cookie = new Cookie(name, null);
        cookie.setPath(path);
        cookie.setMaxAge(maxAge);
        try {
            cookie.setValue(URLEncoder.encode(value, "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addCookie(cookie);
    }

    public void getcookieTest() {
        //package com.foreveross.webbase.common.utils;jwt
        //https://www.cnblogs.com/kxdblog/p/6395839.html
        //https://stackoverflow.com/questions/14566073/setting-cookie-from-dofilter-method
        //https://stackoverflow.com/questions/39334581/request-getcookies-is-always-null

        String cookie = request.getHeader(" ");
        Cookie mycookies[] = request.getCookies();

        //加上前面一行后面即可取到,还是有点莫名其妙。
    }

}
